'''
# Coding:utf-8
# Project: iiop
# Author: rtf
# Time: 2024-06-25 10:56:23
# FileName: read_images.py
# Software: PyCharm
'''


from docx import Document


def test_to_table(doc):
    # 存储表格数据的 HTML 字符串
    html = '<html><body>'

    # 遍历文档中的所有表格
    for table_idx, table in enumerate(doc.tables):
        html += f'<table style="border-collapse: collapse; width: 100%; height: 125.316pt;" border="1">'

        # 记录已合并的单元格
        spanned_cells = set()

        for row_idx, row in enumerate(table.rows):
            html += '<tr>'
            for cell_idx, cell in enumerate(row.cells):
                # 跳过已合并的单元格
                if (row_idx, cell_idx) in spanned_cells:
                    continue

                # 获取单元格的底层 XML 元素
                tc = cell._element

                # 获取单元格的列跨度信息
                grid_span = tc.xpath('.//w:gridSpan/@w:val')
                colspan = int(grid_span[0]) if grid_span else 1

                # 获取单元格的行合并信息
                rowspan = 1
                v_merge = tc.xpath('.//w:vMerge/@w:val')
                current_texts = tc.xpath('.//w:t')
                current_cell_text = ''.join([text.text for text in current_texts])
                if v_merge:
                    if v_merge[0] == 'restart':
                        # 计算跨越的行数，确保不超过表格行数
                        spanned_rows = 1
                        for i in range(row_idx + 1, len(table.rows)):
                            next_cell = table.cell(i, cell_idx)
                            next_v_merge = next_cell._element.xpath('.//w:vMerge/@w:val')
                            next_texts = next_cell._element.xpath('.//w:t')
                            next_cell_text = ''.join([text.text for text in next_texts])
                            if next_v_merge:
                                if next_v_merge[0] == 'continue':
                                    spanned_rows += 1
                                    spanned_cells.add((i, cell_idx))
                                elif current_cell_text == next_cell_text:
                                    spanned_rows += 1
                                    spanned_cells.add((i, cell_idx))
                            else:
                                break
                        rowspan = spanned_rows
                        # 标记已合并的行
                        for i in range(1, spanned_rows):
                            spanned_cells.add((row_idx + i, cell_idx))

                # 获取单元格的文本内容
                cell_text = ''
                for paragraph in cell.paragraphs:
                    cell_text += paragraph.text + '<br>'

                # 添加单元格到 HTML 字符串中
                html += f'<td style="text-align: center" rowspan="{rowspan}" colspan="{colspan}"><span style="font-size: 10.5pt; font-family: 仿宋_GB2312;">{cell_text}</span></td>'

                # 标记已合并的列
                for i in range(rowspan):
                    for j in range(colspan):
                        spanned_cells.add((row_idx + i, cell_idx + j))
            html += '</tr>'
        html += '</table><br /><br />'
    html += '</body></html>'

    # 打印或保存生成的 HTML
    print(html)

    # 如果要保存生成的 HTML 到文件
    with open('generated_table.html', 'w', encoding='utf-8') as file:
        file.write(html)


def table_to_html(doc):
    # 存储表格数据的 HTML 字符串
    tables = list()
    # 遍历文档中的所有表格
    for table_idx, table in enumerate(doc.tables):
        html = f'<table style="border-collapse: collapse; width: 100%; height: 125.316pt;" border="1">'

        # 记录已合并的单元格
        spanned_cells = set()

        for row_idx, row in enumerate(table.rows):
            html += '<tr>'
            for cell_idx, cell in enumerate(row.cells):
                # 跳过已合并的单元格
                if (row_idx, cell_idx) in spanned_cells:
                    continue

                # 获取单元格的底层 XML 元素
                tc = cell._element

                # 获取单元格的列跨度信息
                grid_span = tc.xpath('.//w:gridSpan/@w:val')
                colspan = int(grid_span[0]) if grid_span else 1

                # 获取单元格的行合并信息
                rowspan = 1
                v_merge = tc.xpath('.//w:vMerge/@w:val')
                current_texts = tc.xpath('.//w:t')
                current_cell_text = ''.join([text.text for text in current_texts])
                if v_merge:
                    if v_merge[0] == 'restart':
                        # 计算跨越的行数，确保不超过表格行数
                        spanned_rows = 1
                        for i in range(row_idx + 1, len(table.rows)):
                            next_cell = table.cell(i, cell_idx)
                            next_v_merge = next_cell._element.xpath('.//w:vMerge/@w:val')
                            next_texts = next_cell._element.xpath('.//w:t')
                            next_cell_text = ''.join([text.text for text in next_texts])
                            if next_v_merge:
                                if next_v_merge[0] == 'continue':
                                    spanned_rows += 1
                                    spanned_cells.add((i, cell_idx))
                                elif current_cell_text == next_cell_text:
                                    spanned_rows += 1
                                    spanned_cells.add((i, cell_idx))
                            else:
                                break
                        rowspan = spanned_rows
                        # 标记已合并的行
                        for i in range(1, spanned_rows):
                            spanned_cells.add((row_idx + i, cell_idx))

                # 获取单元格的文本内容
                cell_text = ''
                for paragraph in cell.paragraphs:
                    cell_text += paragraph.text + '<br>'

                # 添加单元格到 HTML 字符串中
                html += f'<td style="text-align: center" rowspan="{rowspan}" colspan="{colspan}"><span style="font-size: 10.5pt; font-family: 仿宋_GB2312;">{cell_text}</span></td>'

                # 标记已合并的列
                for i in range(rowspan):
                    for j in range(colspan):
                        spanned_cells.add((row_idx + i, cell_idx + j))
            html += '</tr>'
        html += '</table>'
        tables.append(html)
    return tables


# 表格的位置
def table_positions(doc):
    table_positions = []
    element_idx = 0

    for block in doc.element.body:
        if block.tag.endswith('tbl'):
            table_positions.append(element_idx)
        element_idx += 1

    return table_positions


# docx_path = '/home/rtf/文档/test_table.docx'
# doc = Document(docx_path)
# table_to_html(doc)
# test_to_table(doc)
#
# table_positions = table_positions(doc)
# print("Table positions in the document:", table_positions)
